package com.bangmai.listener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bangmai.exception.ServiceException;
import com.bangmai.model.GoodMapper;
import com.bangmai.model.MqGood;
import com.bangmai.model.MqOrder;
import com.bangmai.model.Order;
import com.bangmai.model.OrderGoods;
import com.bangmai.model.OrderStatus;
import com.bangmai.service.CustomsService;
import com.bangmai.util.ExecutorPool;
import com.bangmai.util.TimeUtil;
import com.rabbitmq.client.Channel;

@Component
public class RabbitMqListener implements ChannelAwareMessageListener {

	Logger logger = Logger.getLogger(getClass());
	@Autowired
	private CustomsService customsService;
	@Autowired
	private GoodMapper goodMapper;
	@Autowired
	@Qualifier("pool")
	private ExecutorPool pool;// @Qualifier("XXX") 中的 XXX是 Bean 的名称，所以
								// @Autowired 和 @Qualifier 结合使用时，自动注入的策略就从
								// byType 转变成 byName 了。

	public void onMessage(Message message, Channel channel) throws ServiceException {
		// TODO Auto-generated method stub
		byte[] bs = message.getBody();
		try {
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);// 收到消息后
			String jsonString = new String(bs, "utf-8");
			MqOrder mqOrder = MqOrder.json2Bean(jsonString);
			List<MqGood> mqGoods = mqOrder.getGoods_info();
			if (mqGoods==null||mqGoods.isEmpty()) {
				throw new ServiceException("发往海关的订单信息中没有商品！！！");
			}
			List<OrderGoods> orderGoods=new ArrayList<>();
			for (MqGood mqGood : mqGoods) {
				OrderGoods oGoods=new OrderGoods();
				oGoods.setSku(mqGood.getGoods_sku());
				oGoods.setQty(mqGood.getGoods_num());
				oGoods.setDecprice(mqGood.getGoods_price());
				oGoods.setdectotal(mqGood.getGoods_total());
				oGoods.setOrder_id(mqOrder.getOrder_sn());
				orderGoods.add(oGoods);
			}
			
			Order order = new Order();
			order.setOid(mqOrder.getOrder_sn());
			order.setUsername(mqOrder.getBuyer_name());
			order.setUsercard(mqOrder.getCard_num());
			order.setUsercardtype(mqOrder.getCard_type());
			order.setUserphone(mqOrder.getBuyer_phone());
			order.setUseraddress(mqOrder.getReciver_address());
			String[] arr = mqOrder.getReciver_address().trim().split("@");
			List<String> list = Arrays.asList(arr);
			order.setProvince(list.get(0));
			order.setCity(list.get(1));
			order.setDistrict(list.get(2));
			order.setDetailaddress(list.get(3));
			order.setOrdergoodstotal(Float.valueOf(mqOrder.getOrder_amount()));
			order.setOrderdate(String.valueOf(Long.valueOf(mqOrder.getOrder_time())*1000));
			
			order.setFare(Float.valueOf(mqOrder.getShipping_fee()));
			order.setTax(mqOrder.getTax_fee());
			order.setRemark("");
			order.setPayTransactionNo(mqOrder.getAllinpay_trade_no());
			order.setPayChnlID(mqOrder.getPay_way());
			order.setMonetarm(mqOrder.getMoney_type());
			order.setPaydatetime(TimeUtil.long2Date1(Long.valueOf(mqOrder.getAllinpay_pay_time())*1000));
			order.setGoodsbill(mqOrder.getNeed_list());
			order.setInvoice(mqOrder.getNeed_invoice());
			order.setInvoicetitle(mqOrder.getInvoice_title());
			order.setInvoicecontent(mqOrder.getInvoice_content());
			order.setInsurancefee(mqOrder.getSave_price());
			order.setPaymoney(mqOrder.getOrder_amount());
			order.setGoodtype(mqGoods.size()+"");
			List<Map<String, Object>> orderList = customsService.selectOrderStatus(mqOrder.getOrder_sn());
			if (!orderList.isEmpty()) {
				logger.info("订单号为:"+mqOrder.getOrder_sn()+"的订单已经申请过报关");
				customsService.updateOrder(order);
			} else {
				// 往订单报关流程写入记录
				OrderStatus orderStatus = new OrderStatus();
				orderStatus.setOrder_id(mqOrder.getOrder_sn());
				customsService.insertOrder(order,orderStatus,orderGoods);
			}
			
			ExecutorService executor = pool.getInstance();
			executor.execute(new TaskCustom(customsService, mqOrder.getOrder_sn()));
			executor.execute(new TaskCommodityinspection(customsService,mqOrder.getOrder_sn()));
			executor.execute(new TaskPayment(customsService, mqOrder.getOrder_sn()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new ServiceException(e.getMessage());

		}

	}

}
